import sys

from PIL import ImageQt
from UI.Print import Ui_Print

from Class.Area import MyArea
import tempfile
from pdf2image import convert_from_path
from importQT import *

class Reader(QDialog, Ui_Print):
    def __init__(self, parent=None):
        # 继承主窗口类
        super(Reader, self).__init__(parent)
        self.setupUi(self)
        self.current_page = 0
        # 获取屏幕对象
        # self.screen = QDesktopWidget().screenGeometry()
        self.size = (700, 700)  # 存储pdf页面大小
        self.area = MyArea(self)
        self.area.init(self)
        self.verticalLayout.addWidget(self.area)
        self.btnbig.clicked.connect(self.zoom_big)
        self.btnsmall.clicked.connect(self.zoom_small)
        self.btnpageback.clicked.connect(self.switch_pageback)
        self.btnpageforward.clicked.connect(self.switch_pageforward)
        self.btnprint.clicked.connect(self.showPrint)
        self.images = []#存放所有的Qimage
        self.pils = []#存放所有的PIL images
        self.pagecount = 0


    def read_book(self, fname):
        """打开pdf文件"""
        self.pils.clear()
        with tempfile.TemporaryDirectory() as path:
            self.pils = convert_from_path(fname)
        self.images.clear()
        for i in self.pils:
            self.images.append(self.pil2_qimag(i))
        self.pagecount = len(self.pils)
        # 读取当前页
        self.set_page()

    # PIL格式转QPixmap格式
    def pil2_pixmap(self, pil_img):
        pixmap = ImageQt.toqpixmap(pil_img)
        return pixmap

    # PIL格式转QImage格式
    def pil2_qimag(self, pil_img):
        qimag = ImageQt.toqimage(pil_img)
        return qimag

    def switch_pageforward(self):
        if self.current_page < len(self.images) - 1:
            self.current_page += 1
            self.set_page()

    def switch_pageback(self):
        if self.current_page > 0:
            self.current_page -= 1
            self.set_page()

    def set_page(self):
        """获取Qpixmap方案一：由PIL直接转换为Qpixmap,然后进行缩放，显示在Qlabel上，程序单独运行没问题，但是放在大程序里总是异常退出，
                pixmap= self.pil2_pixmap(self.pils[self.current_page])
        #使用scaled方法把 pix_img 的分辨率设置为*像素**像素;KeepAspectRatio 可以保留宽高比
        pixmap1 = pixmap.scaled(self.size[0],self.size[1], QtCore.Qt.KeepAspectRatio, Qt.SmoothTransformation)#等比例缩放
        方案二：由QImage缩放，然后转换为Qpixmao"""
        qimage = self.images[self.current_page].scaled(self.size[0],self.size[1], QtCore.Qt.KeepAspectRatio, Qt.SmoothTransformation)#等比例缩放
        # 在标签上设置图片
        QPixmapCache.clear()
        pixmap = QtGui.QPixmap()
        pixmap.convertFromImage(qimage)
        label = QLabel()  # 括号里加上self就会有个错误警告，估计因为对象销毁问题
        label.setPixmap(pixmap)
        self.area.setWidget(label)
        self.lblPageNo.setText(str(self.current_page +1) + "/" + str(self.pagecount))

    def zoom_big(self):
        a, b = self.size
        a += 200
        b += 200
        self.size = (a, b)
        self.set_page()

    def zoom_small(self):
        a, b = self.size
        if a > 0:
            a -= 200
            b -= 200
            self.size = (a, b)
            self.set_page()

    def get_file(self):
        # 打开单个文件
        fname, _ = QFileDialog.getOpenFileName(self, 'Open files', './', '(*.pdf)')
        return fname

    def showPrint(self):
        # 实例化打印图像对象
        printer = QPrinter()
        printer.setOrientation(QPrinter.Landscape)
        # 打印窗口弹出
        printdialog = QPrintDialog(printer)
        # 绘制
        if printdialog.exec():
            # 调用绘图
            painter = QPainter(printer)
            # 实例化视图窗口
            rect = painter.viewport()
            # 获取图片的尺寸
            size = self.images[0].size()
            # Qt.KeepAspectRatio  保持纵横比
            size.scale(rect.size(), Qt.KeepAspectRatio)
            # 设置窗口的大小为图片的磁村，并在窗口内绘制
            painter.setViewport(rect.x(), rect.y(), size.width(), size.height())
            painter.setWindow(self.images[0].rect())
            painter.begin(self)  # 必须要有begin、end,否则报错QPaintDevice: Cannot destroy paint device that is being painted
            for img in self.images:
                painter.drawImage(0, 0, img)
            painter.end()

# import os
# # import PyQt5
# if __name__ == '__main__':
#     dirname = os.path.dirname(PyQt5.__file__)
#     plugin_path = os.path.join(dirname, "Qt", 'plugins')
#     os.environ['QT_QPA_PLATFORM_PLUGIN_PATH'] = plugin_path
#     inPutPath = os.path.dirname(os.path.abspath(sys.argv[0]))  # 程序运行的绝对路径
#     app = QApplication(sys.argv)
#     # <editor-fold desc="调用PYQT5自带的翻译文件">
#     translator = QTranslator(app)
#     if translator.load("qt_" + QLocale.system().name(), QLibraryInfo.location(QLibraryInfo.TranslationsPath)):
#         app.installTranslator(translator)
#     # </editor-fold>
#     reader = Reader()
#     reader.setAttribute(Qt.WA_DeleteOnClose)
#     fname = reader.get_file()
#     if fname != "":
#         reader.read_book(fname)
#         reader.exec()
#     sys.exit(0)
